package com.xwj.service.impl;

import com.xwj.domain.Order;
import com.xwj.dto.CommonResult;
import com.xwj.enums.ResultCode;
import com.xwj.feign.StorageFeignClient;
import com.xwj.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * @author xwj
 * @date 2020/11/21
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private StorageFeignClient storageFeignClient;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建订单->调用库存服务扣减库存
     *
     * @param order
     */
    @Override
    @GlobalTransactional
    public void create(Order order) {
        log.info("开始新建订单");
        //1、新建订单
        KeyHolder keyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator preparedStatementCreator = con -> {
            PreparedStatement ps = con.prepareStatement("insert into t_order(user_id,product_id,count,money,status) values(?,?,?,?,?)",
                    Statement.RETURN_GENERATED_KEYS);
            ps.setObject(1, order.getUserId());
            ps.setObject(2, order.getProductId());
            ps.setObject(3, order.getCount());
            ps.setObject(4, order.getMoney());
            ps.setObject(5, 1);
            return ps;
        };
        jdbcTemplate.update(preparedStatementCreator, keyHolder);
        order.setId(keyHolder.getKey().longValue());
        //2、扣减库存
        log.info("开始调用减库存服务");
        CommonResult result = storageFeignClient.decrease(order.getProductId(), order.getCount());
        log.info("结束调用减库存服务");
        if (result.getCode() == ResultCode.SUCCESS.getCode()) {
        } else {
            throw new RuntimeException("库存不足");
        }
        log.info("订单结束");
    }
}
